<template>
    <div class="meeting-detail">
        <!-- 头部导航 -->
        <header class="header">
            <div class="back-btn" @click="handleBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
                <span>返回</span>
            </div>
            <h1>会议详情</h1>
            <Time />

        </header>

        <div class="main-container">
            <div class="form-container" v-loading="loading" element-loading-text="加载中..."
                element-loading-background="rgba(0,0,0,0)">
                <!-- 会议题目 -->
                <div class="form-item">
                    <label>会议题目</label>
                    <template v-if="isEditing">
                        <input v-model="editForm.title" placeholder="请输入会议题目" />
                    </template>
                    <template v-else>
                        <div class="detail-text">{{ meetingDetail.meetingInfo?.title }}</div>
                    </template>
                </div>

                <!-- 会议简介 -->
                <div class="form-item">
                    <label>会议简介</label>
                    <template v-if="isEditing">
                        <textarea v-model="editForm.introduction" rows="4" placeholder="请输入会议简介"
                            style="font-family: '微软雅黑';width: 97.5%;"></textarea>
                        <div class="word-count">{{ editForm.introduction.length }}/200</div>
                    </template>
                    <template v-else>
                        <div class="detail-text description">{{ meetingDetail.meetingInfo?.introduction }}</div>
                    </template>
                </div>

                <!-- 主办方和会议签到时间在同一行 -->
                <div class="form-row">
                    <div class="form-item">
                        <label>主办方</label>
                        <template v-if="isEditing">
                            <input v-model="editForm.organizer" placeholder="请输入主办方" />
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ meetingDetail.meetingInfo?.organizer }}</div>
                        </template>
                    </div>

                    <div class="form-item date-picker-group">
                        <label>会议签到时间</label>
                        <template v-if="isEditing">
                            <div class="date-range-wrapper">
                                <el-date-picker v-model="dateRange[0]" type="datetime" placeholder="开始日期时间"
                                    class="date-picker" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
                                <span class="separator">至</span>
                                <el-date-picker v-model="dateRange[1]" type="datetime" placeholder="结束日期时间"
                                    class="date-picker" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
                            </div>
                        </template>
                        <template v-else>
                            <div class="detail-text">
                                {{ formatDate(meetingDetail.meetingInfo?.startTime) }} 至
                                {{ formatDate(meetingDetail.meetingInfo?.endTime) }}

                            </div>
                        </template>
                    </div>
                </div>

                <!-- 会议地点和具体地点 -->
                <div class="location-row">
                    <div class="form-item">
                        <label>会议地点(签到地点)</label>
                        <template v-if="isEditing">
                            <div class="location-input-wrapper">
                                <el-input v-model="editForm.location1" placeholder="请输入会议地点"
                                    @input="handleLocationSearch" class="location-input" />
                                <div v-show="searchResults.length > 0" class="location-suggestions">
                                    <div v-for="(item, index) in searchResults" :key="index" class="suggestion-item"
                                        @click="selectLocation(item)">
                                        <span class="name">{{ item.name }}</span>
                                        <span class="address">{{ item.address }}</span>
                                    </div>
                                </div>
                            </div>
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ meetingDetail.meetingInfo?.location1 }}</div>
                        </template>
                    </div>
                    <div class="form-item">
                        <label>具体地点</label>
                        <template v-if="isEditing">
                            <input v-model="editForm.location2" placeholder="请输入具体地点" />
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ meetingDetail.meetingInfo?.location2 }}</div>
                        </template>
                    </div>
                    <div class="upload-btn-wrapper" v-if="isEditing">
                        <el-upload class="meeting-upload" :action="'/api/admins/uploadCoverImg'"
                            :headers="uploadHeaders" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                            :before-upload="beforeUpload" :on-progress="handleUploadProgress" :limit="4"
                            :on-exceed="handleExceed" :file-list="[]" :show-file-list="false">
                            <el-button type="danger" :loading="uploadLoading" :disabled="editForm.files.length >= 4">
                                {{ uploadLoading ? '正在上传' : '上传会议附件' }}
                            </el-button>
                        </el-upload>
                        <div class="el-upload__tip">最多上传4个附件，每个附件不大于30MB</div>
                    </div>
                </div>

                <!-- 会议附件列表 -->
                <div class="form-item" v-if="meetingDetail.attachments?.length || editForm.files.length">
                    <div class="file-list-wrapper">
                        <label>会议附件</label>
                        <template v-if="isEditing">
                            <div v-for="(file, index) in editForm.files" :key="index" class="file-item">
                                <div class="file-info">
                                    <a :href="file.url" :download="file.name" target="_blank" class="file-name"
                                        @click.stop>
                                        {{ file.name }}
                                    </a>
                                </div>
                                <el-icon class="delete-icon" @click.stop="removeFile(index)">
                                    <Delete />
                                </el-icon>
                            </div>
                        </template>
                        <template v-else>
                            <div v-for="(file, index) in meetingDetail.attachments" :key="index" class="file-item">
                                <div class="file-info">
                                    <a :href="file.filePath" :download="file.fileName" target="_blank" class="file-name"
                                        @click.stop>
                                        {{ file.fileName }}
                                    </a>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- 签到统计 -->
                <div class="form-item">
                    <label>签到统计</label>
                    <div class="sign-stats">
                        <div class="stat-item">
                            <span class="label">总人数：</span>
                            <span class="value" style="font-size: 25px;color: blue;">{{ meetingDetail.totalParticipants
                                }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">已签到：</span>
                            <span class="value" style="font-size: 25px;color: green;">{{ meetingDetail.signedCount
                                }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">未签到：</span>
                            <span class="value" style="font-size: 25px;color: red;">{{ meetingDetail.unsignedCount
                                }}</span>
                        </div>
                        <!-- <div class="stat-item">
                            <span class="label">签到状态：</span>
                            <span class="value" :class="{ 'signed': meetingDetail.meetingInfo?.signStatus === '已签齐' }">
                                {{ meetingDetail.meetingInfo?.signStatus }}
                            </span>
                        </div> -->
                    </div>
                </div>

                <!-- 参会人列表 -->
                <div class="form-item">
                    <label>参会人名单</label>
                    <div class="participants-list">
                        <template v-if="isEditing">
                            <div class="invite-section">
                                <el-input v-model="searchKeyword" placeholder="支持搜索姓名、手机号、所属单位、ID" class="search-input"
                                    @keyup.enter="handleSearch">
                                    <template #suffix>
                                        <el-icon class="search-icon" @click="handleSearch">
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>

                                <div class="filter-section">
                                    <el-select v-model="filters.identity" placeholder="身份" class="filter-item">
                                        <el-option label="身份筛选：全部" value="all" />
                                        <el-option label="市级政协委员" value="city" />
                                    </el-select>
                                    <el-select v-model="filters.region" placeholder="地区" class="filter-item">
                                        <el-option label="地区筛选：全部" value="all" />
                                    </el-select>
                                    <el-select v-model="filters.affiliation" placeholder="界别" class="filter-item">
                                        <el-option label="界别筛选：全部" value="all" />
                                    </el-select>
                                    <el-button type="danger" @click="addSelectedParticipants"
                                        :disabled="currentSelection.length === 0">
                                        添加所选
                                    </el-button>
                                </div>

                                <el-table ref="participantsTable" :data="participantsList"
                                    @selection-change="handleSelectionChange" class="participants-table"
                                    v-loading="participantsLoading">
                                    <el-table-column type="selection" width="55"
                                        :selectable="(row) => !isParticipantSelected(row)" />
                                    <el-table-column prop="uname" label="姓名" />
                                    <el-table-column prop="identity" label="身份" />
                                    <el-table-column prop="region" label="地区" />
                                    <el-table-column prop="affiliation" label="界别" />
                                </el-table>
                            </div>

                            <div class="selected-participants">
                                <el-table :data="editForm.participants" @selection-change="handleSelectedListChange"
                                    class="selected-table">
                                    <el-table-column width="55">
                                        <template #header>
                                            <span>{{ editForm.participants.length }}人</span>
                                        </template>
                                        <template #default="scope">
                                            <el-icon :class="['delete-icon', { 'selected': scope.row.isSelected }]"
                                                @click="toggleParticipantSelection(scope.row)" style="cursor: pointer;">
                                                <Delete />
                                            </el-icon>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="uname" label="姓名" />
                                    <el-table-column prop="identity" label="身份" />
                                    <el-table-column prop="region" label="地区" />
                                    <el-table-column prop="affiliation" label="界别" />
                                    <el-table-column width="120">
                                        <template #header>
                                            <el-button type="danger" size="small" @click="removeSelectedParticipants"
                                                :disabled="!hasSelectedToRemove">
                                                删除所选
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </template>
                        <template v-else>
                            <el-table :data="meetingDetail.participants" class="participants-table">
                                <el-table-column prop="uname" label="姓名" />
                                <el-table-column prop="phone" label="手机号" />
                                <el-table-column prop="identity" label="身份" />
                                <el-table-column prop="region" label="地区" />
                                <el-table-column prop="affiliation" label="界别" />
                                <el-table-column prop="mpStatus" label="签到状态">
                                    <template #default="scope">
                                        <span :class="{ 'signed': scope.row.mpStatus === '已签到' }">
                                            {{ scope.row.mpStatus }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </div>
                </div>
            </div>

            <!-- 底部按钮 -->
            <div class="form-actions">
                <template v-if="isEditing">
                    <el-button @click="cancelEdit">取消</el-button>
                    <el-button type="danger" @click="submitEdit">保存</el-button>
                </template>
                <template v-else>
                    <el-button v-if="allowEdit" type="danger" @click="startEdit">修改</el-button>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Search, Delete } from '@element-plus/icons-vue'
import { getMeetingDetail, getParticipants, updateMeeting } from '@/api/meetings'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import AMapLoader from '@amap/amap-jsapi-loader'
import Time from '@/components/Time.vue'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const participantsLoading = ref(false)
const uploadLoading = ref(false)
const meetingDetail = ref({})
const isEditing = ref(false)
const searchResults = ref([])
const searchKeyword = ref('')
const participantsList = ref([])
const currentSelection = ref([])
const selectedToRemove = ref([])
const participantsTable = ref(null)
const dateRange = ref([])
const filters = ref({
    identity: 'all',
    region: 'all',
    affiliation: 'all'
})

let autoComplete = null

const tokenStore = useTokenStore()

const uploadHeaders = computed(() => ({
    'Authorization': tokenStore.token
}))

// 编辑表单
const editForm = ref({
    title: '',
    introduction: '',
    organizer: '',
    location1: '',
    location2: '',
    files: [],
    participants: [],
    deleteFileIds: []
})

// 添加一个计算属性来判断是否允许编辑
const allowEdit = computed(() => {
    return route.query.from !== 'ended'
})

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 初始化高德地图
const initAMap = async () => {
    try {
        window._AMapSecurityConfig = {
            securityJsCode: '471c055f43738d0a48758620c81ed465',
        }

        await AMapLoader.load({
            key: '6b8b624eb7c617e7c16e2eb2941b2081',
            version: '2.0',
            plugins: ['AMap.AutoComplete']
        })

        autoComplete = new AMap.AutoComplete({
            city: '全国'
        })
    } catch (error) {
        console.error('地图初始化失败:', error)
    }
}

// 处理地址搜索
const handleLocationSearch = async (value) => {
    if (!value) {
        searchResults.value = []
        return
    }

    try {
        if (!autoComplete) return

        autoComplete.search(value, (status, result) => {
            if (status === 'complete' && result.tips) {
                searchResults.value = result.tips.map(tip => ({
                    name: tip.name,
                    address: tip.district + tip.address,
                    location: tip.location,
                    district: tip.district
                }))
            }
        })
    } catch (error) {
        console.error('地址搜索失败:', error)
    }
}

// 选择地址
const selectLocation = (item) => {
    editForm.value.location1 = item.name
    editForm.value.location2 = item.address
    searchResults.value = []
}


// 获取会议详情
const fetchMeetingDetail = async () => {
    loading.value = true
    try {
        const mid = route.params.mid
        console.log('Fetching meeting detail for mid:', mid)

        const response = await getMeetingDetail(mid)
        console.log('API Response:', response)

        if (response.code === 200) {
            meetingDetail.value = response.data
            // 初始化编辑表单
            initEditForm()
        } else {
            ElMessage.error(response.msg || '获取会议详情失败')
        }
    } catch (error) {
        console.error('获取会议详情失败:', error)
        ElMessage.error('获取会议详情失败')
    } finally {
        loading.value = false
    }
}

// 初始化编辑表单
const initEditForm = () => {
    const info = meetingDetail.value.meetingInfo
    if (!info) return

    editForm.value = {
        mid: info.mid,
        title: info.title,
        introduction: info.introduction,
        organizer: info.organizer,
        location1: info.location1,
        location2: info.location2,
        files: meetingDetail.value.attachments?.map(file => ({
            aid: file.aid,
            name: file.fileName,
            url: file.filePath
        })) || [],
        participants: meetingDetail.value.participants || [],
        deleteFileIds: []
    }

    // 处理日期格式
    dateRange.value = [
        info.startTime.substring(0, 16), // 只取到分钟
        info.endTime.substring(0, 16)
    ]

    // 调试输出
    console.log('Meeting Detail:', meetingDetail.value)
    console.log('Edit Form:', editForm.value)
    console.log('Date Range:', dateRange.value)
}

// 开始编辑
const startEdit = () => {
    isEditing.value = true
    initEditForm()
}

// 取消编辑
const cancelEdit = () => {
    ElMessageBox.confirm('确定要取消编辑吗？未保存的修改将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        isEditing.value = false
        initEditForm()
    }).catch(() => { })
}

// 提交编辑
const submitEdit = async () => {
    try {
        const updateData = {
            mid: editForm.value.mid,
            title: editForm.value.title,
            introduction: editForm.value.introduction,
            organizer: editForm.value.organizer,
            startTime: dateRange.value[0],
            endTime: dateRange.value[1],
            location1: editForm.value.location1,
            location2: editForm.value.location2,
            files: editForm.value.files.map(file => ({ url: file.url })),
            deleteFileIds: editForm.value.deleteFileIds,
            participantIds: editForm.value.participants.map(p => p.uid)
        }

        const response = await updateMeeting(updateData)
        if (response.code === 200) {
            ElMessage.success('修改成功')
            isEditing.value = false
            fetchMeetingDetail()
        } else {
            ElMessage.error(response.msg || '修改失败')
        }
    } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败')
    }
}

// 处理文件上传成功
const handleUploadSuccess = (response, file) => {
    uploadLoading.value = false
    if (response.code === 200) {
        editForm.value.files.push({
            name: file.name,
            url: response.data
        })
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.msg || '上传失败')
    }
}

// 处理文件上传失败
const handleUploadError = (error) => {
    uploadLoading.value = false
    console.error('上传错误:', error)
    ElMessage.error('文件上传失败')
}

// 处理文件超出限制
const handleExceed = () => {
    ElMessage.warning('最多只能上传4个附件')
}

// 上传前的验证
const beforeUpload = (file) => {
    const isLt30M = file.size / 1024 / 1024 < 30
    if (!isLt30M) {
        ElMessage.error('文件大小不能超过 30MB!')
        return false
    }

    if (editForm.value.files.length >= 4) {
        ElMessage.error('最多只能上传4个附件!')
        return false
    }
    return true
}

// 移除文件
const removeFile = (index) => {
    const file = editForm.value.files[index]
    if (file.aid) {
        editForm.value.deleteFileIds.push(file.aid)
    }
    editForm.value.files.splice(index, 1)
}

// 获取参会人列表
const fetchParticipants = async () => {
    participantsLoading.value = true
    try {
        const response = await getParticipants({
            searchText: searchKeyword.value,
            identity: filters.value.identity === 'all' ? '' : filters.value.identity,
            region: filters.value.region === 'all' ? '' : filters.value.region,
            affiliation: filters.value.affiliation === 'all' ? '' : filters.value.affiliation
        })
        if (response.code === 200) {
            participantsList.value = response.data
        } else {
            ElMessage.error(response.msg || '获取参会人列表失败')
        }
    } catch (error) {
        console.error('获取参会人列表错误:', error)
        ElMessage.error('获取参会人列表失败')
    } finally {
        participantsLoading.value = false
    }
}

// 搜索参会人
const handleSearch = () => {
    fetchParticipants()
}

// 判断参会人是否已被选中
const isParticipantSelected = (participant) => {
    return editForm.value.participants.some(p => p.uid === participant.uid)
}

// 处理选择变化
const handleSelectionChange = (val) => {
    currentSelection.value = val
}

// 添加所选参会人
const addSelectedParticipants = () => {
    if (currentSelection.value.length === 0) return

    const newParticipants = currentSelection.value.map(item => ({
        ...item,
        isSelected: false
    }))

    editForm.value.participants = [...editForm.value.participants, ...newParticipants]
    currentSelection.value = []

    if (participantsTable.value) {
        participantsTable.value.clearSelection()
    }
}

// 处理参会人名单的选择变化
const handleSelectedListChange = (val) => {
    selectedToRemove.value = val
}

// 移除选中的参会人
const removeSelectedParticipants = () => {
    if (selectedToRemove.value.length === 0) {
        ElMessage.warning('请先选择要删除的参会人')
        return
    }

    editForm.value.participants = editForm.value.participants.filter(item =>
        !selectedToRemove.value.some(selected => selected.uid === item.uid)
    )

    selectedToRemove.value = []
}

// 切换参会人选择状态
const toggleParticipantSelection = (participant) => {
    participant.isSelected = !participant.isSelected
    if (participant.isSelected) {
        if (!selectedToRemove.value.some(p => p.uid === participant.uid)) {
            selectedToRemove.value.push(participant)
        }
    } else {
        selectedToRemove.value = selectedToRemove.value.filter(p => p.uid !== participant.uid)
    }
}

const hasSelectedToRemove = computed(() => {
    return selectedToRemove.value.length > 0
})

// 返回上一页
const handleBack = () => {
    if (isEditing.value) {
        ElMessageBox.confirm('确定要离开吗？未保存的修改将会丢失', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            router.back()
        }).catch(() => { })
    } else {
        router.back()
    }
}

// 添加上传进度处理函数
const handleUploadProgress = () => {
    uploadLoading.value = true
}

onMounted(() => {
    fetchMeetingDetail()
    initAMap()
    fetchParticipants()
})
</script>

<style scoped>
@import '@/assets/css/meeting/addMeeting.css';
@import '@/assets/css/header/index.css';

.meeting-detail {
    margin-top: -50px;
    height: 100%;
    overflow-y: auto;
}

.detail-text {
    padding: 8px 12px;
    background-color: #ffffff;
    border-radius: 4px;
    min-height: 20px;
    line-height: 1.5;
}

.detail-text.description {
    min-height: 80px;
    white-space: pre-wrap;
}

.sign-stats {
    display: flex;
    gap: 20px;
    margin-top: 10px;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
}

.stat-item .label {
    color: #606266;
}

.stat-item .value {
    font-weight: bold;
    color: #303133;
}

.signed {
    color: #67c23a;
}

.participants-list {
    margin-top: 10px;
}

.participants-table {
    width: 100%;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 8px;
}

.file-name {
    color: #409eff;
    text-decoration: none;
}

.file-name:hover {
    text-decoration: underline;
}

.delete-icon {
    margin-left: auto;
    color: #ffffff;
    cursor: pointer;
}

.delete-icon:hover {
    color: #ffffff;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
    padding: 20px 0;
}

.invite-section {
    margin-bottom: 20px;
}

.filter-section {
    margin: 15px 0;
    display: flex;
    gap: 10px;
}

.filter-item {
    width: 150px;
}

.selected-participants {
    margin-top: 20px;
}
</style>
